﻿using Atlanchim.Crm.Mui.Pages;
using FirstFloor.ModernUI.Windows.Controls;
using Lmondeil.Crm.EF;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Windows.Input;
using CrmEntities = Lmondeil.Crm.EF;

namespace Atlanchim.Crm.Mui.Helpers
{
    public static class CrmCrudHelper
    {
        public static void OnCanDeleteEntity(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = e.Parameter is AbstractPageViewModel;
        }

        public static void OnDeleteEntity(object target, ExecutedRoutedEventArgs e)
        {
            if (e.Parameter is AbstractPageViewModel)
            {
                ((AbstractPageViewModel)e.Parameter).DeleteEntity();
            }
        }

        #region Suppressions

        public static void DeleteEntityNewContext(object entity)
        {
            using (CrmContext context = new CrmContext())
            {
                try
                {
                    bool bDeleted = false;

                    if (entity is Societe)
                    {
                        DeleteSocieteNewContext(context, (Societe)entity);
                        bDeleted = true;
                    }
                    if (entity is Contact)
                    {
                        DeleteContactNewContext(context, (Contact)entity);
                        bDeleted = true;
                    }
                    if (entity is CrmEntities.Action)
                    {
                        DeleteActionNewContext(context, (CrmEntities.Action)entity);
                        bDeleted = true;
                        if (entity is Adresse)
                        {
                            DeleteAdresseNewContext(context, (Adresse)entity);
                            bDeleted = true;
                        }
                        if (entity is Email)
                        {
                            DeleteEmailNewContext(context, (Email)entity);
                            bDeleted = true;
                        }
                        if (entity is Telephone)
                        {
                            DeleteTelephoneNewContext(context, (Telephone)entity);
                            bDeleted = true;
                        }
                        if (entity is Document)
                        {
                            DeleteDocumentNewContext(context, (Document)entity);
                            bDeleted = true;
                        }

                        // FeedBack
                        if (bDeleted)
                        {
                            string message = "Suppression effectuée avec succès.";
                            ModernDialog.ShowMessage(message, "Succès", System.Windows.MessageBoxButton.OK);
                        }
                        else
                        {
                            string message = "Aucune suppression n'a été effectuée.";
                            ModernDialog.ShowMessage(message, "Echec", System.Windows.MessageBoxButton.OK);
                        }
                    }
                }
                catch (DbEntityValidationException deleteEntityException)
                {
                    PersistenceErrorHelper.ShowErrors(deleteEntityException);
                }
                catch (Exception deleteException)
                {
                    string message = "Une erreur technique est survenue : " + deleteException.Message;
                    ModernDialog.ShowMessage(message, "Erreur", System.Windows.MessageBoxButton.OK);
                }
            }
        }

        private static void DeleteTelephoneNewContext(CrmContext context, Telephone telephone)
        {
            context.Telephones.Attach(telephone);
            context.Telephones.Remove(telephone);
            context.SaveChanges();
        }

        private static void DeleteEmailNewContext(CrmContext context, Email email)
        {
            context.Emails.Attach(email);
            context.Emails.Remove(email);
            context.SaveChanges();
        }

        private static void DeleteActionNewContext(CrmContext context, CrmEntities.Action action)
        {
            context.Actions.Attach(action);
            context.Actions.Remove(action);
            context.SaveChanges();
        }

        private static void DeleteSocieteNewContext(CrmContext context, Societe societe)
        {
            context.Societes.Attach(societe);

            // Suppression de toutes les adresses
            List<Adresse> adresses = societe.Adresses.ToList();
            foreach (Adresse adresse in adresses)
            {
                context.Adresses.Remove(adresse);
            }

            // Détachement de tous les contacts
            List<Contact> contacts = societe.Contacts.ToList();
            foreach (Contact contact in contacts)
            {
                societe.Contacts.Remove(contact);
            }

            context.Societes.Remove(societe);
            context.SaveChanges();
        }

        /// <summary>
        /// Suppression d'un contact
        /// </summary>
        /// <param name="context"></param>
        /// <param name="contact"></param>
        private static void DeleteContactNewContext(CrmContext context, Contact contact)
        {
            context.Contacts.Attach(contact);

            // Suppression de toutes les actions
            List<CrmEntities.Action> actions = contact.Actions.ToList();
            foreach (CrmEntities.Action action in actions)
            {
                context.Actions.Remove(action);
            }


            // Suppression de toutes les alertes
            List<Alerte> alertes = contact.Alertes.ToList();
            foreach (Alerte alerte in alertes)
            {
                context.Alertes.Remove(alerte);
            }


            context.Contacts.Remove(contact);
            context.SaveChanges();
        }

        /// <summary>
        /// Suppression d'une adresse
        /// </summary>
        /// <param name="context"></param>
        /// <param name="adresse"></param>
        private static void DeleteAdresseNewContext(CrmContext context, Adresse adresse)
        {
            context.Adresses.Attach(adresse);
            context.Adresses.Remove(adresse);
            context.SaveChanges();
        }

        /// <summary>
        /// Supression d'un document
        /// </summary>
        /// <param name="context"></param>
        /// <param name="adresse"></param>
        private static void DeleteDocumentNewContext(CrmContext context, Document document)
        {
            context.Documents.Attach(document);
            context.Documents.Remove(document);
            context.SaveChanges();
        }
        #endregion Suppressions

        #region parameters
        /// <summary>
        /// Persistence d'un paramètre
        /// </summary>
        /// <param name="parameterKey"></param>
        /// <param name="parameterValue"></param>
        public static void SetParameter(string parameterKey, string parameterValue)
        {
            try
            {
                using (CrmContext context = new CrmContext())
                {
                    CrmParametre parameter = context.CrmParametres
                                                    .Where(param => param.Key == parameterKey)
                                                    .FirstOrDefault();

                    if (parameter == null)
                    {
                        parameter = new CrmParametre()
                        {
                            Key = parameterKey
                        };
                        context.CrmParametres.Add(parameter);
                    }

                    parameter.Value = parameterValue;
                    context.SaveChanges();
                }
            }
            catch (DbEntityValidationException deleteEntityException)
            {
                PersistenceErrorHelper.ShowErrors(deleteEntityException);
            }
            catch (Exception persistExc)
            {
                ModernDialog.ShowMessage("Erreur technique : " + Environment.NewLine + persistExc.Message, "ERREUR", System.Windows.MessageBoxButton.OK);
            }
        }

        /// <summary>
        /// Récupération d'un paramètre
        /// </summary>
        /// <param name="parameterKey"></param>
        /// <param name="parameterValue"></param>
        public static string GetParameter(string parameterKey)
        {
            string result = string.Empty;

            try
            {
                using (CrmContext context = new CrmContext())
                {
                    CrmParametre parameter = context.CrmParametres
                                                    .Where(param => param.Key == parameterKey)
                                                    .FirstOrDefault();

                    if (parameter != null)
                    {
                        result = parameter.Value;
                    }
                }
            }
            catch (DbEntityValidationException deleteEntityException)
            {
                PersistenceErrorHelper.ShowErrors(deleteEntityException);
            }
            catch (Exception getExc)
            {
                ModernDialog.ShowMessage("Erreur technique : " + Environment.NewLine + getExc.Message, "ERREUR", System.Windows.MessageBoxButton.OK);
            }

            return result;
        }
        #endregion parameters
    }
}
